import os
import easyocr
import pandas as pd
from PIL import Image
import re
from datetime import datetime

def extract_keywords(text):
    # 合并后的正则表达式：
    # 1. 匹配手机号码（1开头，11位）|
    # 2. 匹配其他关键词（6-20位字母数字下划线减号）
    pattern = r'(?:1[3-9]\d{9}|[a-zA-Z0-9_-]{6,20})'

    keywords = re.findall(pattern, text)
    # 去重（保留顺序）
    return list(dict.fromkeys(keywords))


def easyocr_nested_folders(root_folder,formatted_date,log_callback):
    """
    使用EasyOCR递归识别两层文件夹中的图片文字
    :param root_folder: 根文件夹路径

    """
    # 支持的图片格式
    supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.gif')

    # 初始化EasyOCR阅读器（中文+英文）
    reader = easyocr.Reader(['ch_sim', 'en'])

    # 收集所有结果
    results = []
    # 遍历根文件夹
    for dir1 in os.listdir(root_folder):
        dir1_path = os.path.join(root_folder, dir1)

        if not os.path.isdir(dir1_path):
            continue
        print(dir1_path)
        # 遍历第二层文件夹
        for filename in os.listdir(dir1_path):
            filepath = os.path.join(dir1_path, filename)
            print(filepath)
            try:
                # 使用OCR识别文字
                img = Image.open(filepath)
                ocr_results = reader.readtext(img, detail=0)
                info = ' '.join(ocr_results[1:len(ocr_results) - 1])

                keywords = extract_keywords(info)
                # 添加到结果列表
                results.append({
                    'keyword': dir1,
                    "name": ocr_results[0],
                    "info": info,
                    'wechat': '  '.join(keywords)
                })
                log_callback(f"Processed: {dir1}/{filename}")
                print(f"Processed: {dir1}/{filename}")

            except Exception as e:
                log_callback(f"Error processing {dir1}/{filename}: {str(e)}")
                print(f"Error processing {dir1}/{filename}: {str(e)}")
                results.append({
                    'folder_level1': dir1,
                    'text': f'ERROR: {str(e)}'
                })

    # 将结果保存为CSV文件
    if results:
        df = pd.DataFrame(results)
        filename = f"微信视频号数据采集_{formatted_date}.xlsx"
        df.to_excel(filename, index=False)
        print(f"OCR results saved to {filename}")
        log_callback(f"OCR results saved to {filename}")
        return df
    else:
        print("No images processed.")
        log_callback(f"No images processed.")
        return None


#now = datetime.now()
#formatted_date = now.strftime("%Y_%m_%d")
#formatted_date = "2025_07_18"
# # 使用示例
# folder_path = 'E:\\project\\auto_project\\mixpython\\'+formatted_date  # 替换为你的图片文件夹路径
#relative_path = os.path.join(formatted_date)
#easyocr_nested_folders(relative_path,formatted_date)
